<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        #big{
            width: 500px;
            height: 500px;
            background: darkcyan;
            margin: 0 auto;
            position: relative;
        }
        #box{
            position: absolute;
            width: 150px;
            height: 150px;
            background: rgb(226, 195, 137);
            opacity: 0.8;
        }
    </style>
</head>
<body>
    <div id="big">
        <div id="box"></div>
    </div>
    <script>
        var big = document.getElementById("big")
        var box = document.getElementById("box")

        box.onmousedown = function(e){
            //获取当前坐标
            var nowX = e.pageX
            var nowY = e.pageY
            var left = box.offsetLeft
            var top= box.offsetTop
            document.onmousemove = function(e){
                var newX = e.pageX
                var newY = e.pageY
                var resX = newX - nowX + left
                var resY = newY - nowY + top
                if(resX < 0){
                    resX = 0
                }
                if(resX > big.clientWidth - box.clientWidth){
                    resX = big.clientWidth - box.clientWidth
                }
                if(resY < 0){
                    resY = 0
                }
                if(resY > big.clientHeight - box.clientHeight){
                    resY = big.clientHeight - box.clientHeight
                }
                box.style.left = resX + "px"
                box.style.top = resY + "px"

                
            }
        }
        box.onmouseup = function(){
            document.onmousemove = null
        }

    </script>
</body>
</html>